package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;


import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.ReflectionUtils;
import com.mjk.common.web.getway.constns.GetWayError;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;

import java.util.Map;

/**
 * 网管协议 判断 拦截器
 * @author mjk
 *
 */
@BeeGetWayInterceptor(value=-999,interceptorType={GetWayInterceptorType.ALL})
public class GetWayProtocalInterceptor implements GetWayInterceptor {
				
	@Override
	public BeeResponse interceptor(GetWayInterceptorReq request,
								   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
		//协议调用 构建参数，需要吧restful参数带入参数
		Map<String, Object> params = request.getParams();
		params.putAll(request.getRestfulParams());		
		Object o = request.getProtocal().invoke(params);	
		next.proceed(request);
		return getWaySucReturn(o);
	}
	
	@SuppressWarnings("rawtypes")
	public BeeResponse getWaySucReturn(Object o){
		if(o instanceof BeeResponse rsp){
			return rsp;
		}
		BeeResponse response = new BeeResponse();
		if(ObjectUtils.isNotEmpty(o)){
			if(o instanceof Map map){
				response.setCode(Integer.valueOf(map.get("code").toString()));
				response.setMsg(ObjectUtils.isEmpty(map.get("msg"))?"":map.get("msg").toString());
				response.setData(map.get("data"));
			}else if(o instanceof String str){
				response = GsonUtils.json2Bean(str, BeeResponse.class);
			}else{
				if(ObjectUtils.isNotEmpty(ReflectionUtils.getField(o.getClass(), "code"))){
					Integer code = (Integer) ReflectionUtils.getFieldValue(o, "code");
					if(ObjectUtils.isNotEmpty(code)){
						response.setCode(code);
					}else{
						response.setCode(GetWayError.SUC.getCode());
					}
				}
				if(ObjectUtils.isNotEmpty(ReflectionUtils.getField(o.getClass(), "msg"))){
					String msg = (String) ReflectionUtils.getFieldValue(o, "msg");
					if(ObjectUtils.isNotEmpty(msg)){
						response.setMsg(msg);
					}else{
						response.setMsg(GetWayError.SUC.getMsg());
					}
				}
				response.setData(ReflectionUtils.getFieldValue(o, "data"));
				}
		}
		return response;
	}
}
